package mx.com.mindbits.bandpay.asynctask;

import mx.com.mindbits.bandpay.R;
import mx.com.mindbits.bandpay.utils.ConstantsValues;
import mx.com.mindbits.emvcardreader.usbinterface.CardCommands;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class OpenDeviceTask extends AsyncTask <Void, Void, CardCommands>{
	private ProgressDialog dialog;
	private Context contexto;
	private CardCommands readerDevice;
	
	
	public OpenDeviceTask(CardCommands readerDevice, Context contexto){
		this.readerDevice = readerDevice;
		this.contexto = contexto;
	}
	
	@Override
	protected void onPreExecute(){
		super.onPreExecute();
		try{
			dialog = new ProgressDialog(contexto);
			dialog.setTitle(R.string.progress_dialog_title1);
			dialog.setMessage("Abriendo dispositivo USB");
			dialog.setCancelable(false);
			dialog.show();
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	@Override
	protected CardCommands doInBackground(Void... params) {		
		try{			
			if(!readerDevice.getReader().isOpened()){
				readerDevice.ConnectingDevice();
				ConstantsValues.REQUEST_SENDED = true;
				Log.d(ConstantsValues.TAG_READER, "Abriendo puerto USB: [ASYNCTASK]");
			}
		}catch(Exception e){
			Log.e(ConstantsValues.TAG_READER, "Error al abrir el dispositivo: "+e);			
		}		 
		return readerDevice;
	}
	
	@Override
	protected void onPostExecute(CardCommands cardCommands){
		if (cardCommands.getReader().isOpened()){
			dialog.dismiss();			
			ConstantsValues.tarjeta = readerDevice;
			Log.d(ConstantsValues.TAG_READER, "Dispositivo abierto");
		}else{
			dialog.dismiss();
			
		}
	}

}
